import { defineStore } from 'pinia';
import { TOKEN_NAME } from '@/config/global';

const UserItem = {
  roles: []
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME) || '',
    userInfo: { ...UserItem }
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    }
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const mockLogin = async (userInfo: Record<string, unknown>) => {
        console.log(userInfo);
        return {
          code: 200,
          message: '登陆成功',
          data: 'main_token'
        };
      };
      const res = await mockLogin(userInfo);
      if (res.code === 200) {
        this.token = res.data;
      } else {
        throw res;
      }
    }
  },
  persist: {
    // afterRestore: (ctx) => {}
  }
});
